package cn.org.wangchangjiu.table2entity.util;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.codeStyle.CodeStyleManager;

import java.io.IOException;


public class LocalFileUtils {

    public static PsiDirectory getChildDirNotExistCreate(Project project, VirtualFile root, String childPackage) throws IOException {
        if (root == null || childPackage == null || childPackage == "") {
            return null;
        }
        String[] childs = childPackage.split("\\.");
        VirtualFile childFile = root;
        for (String child : childs) {
            VirtualFile existChildFile = childFile.findChild(child);
            if (existChildFile != null) {
                childFile = existChildFile;
            } else {
                childFile = childFile.createChildDirectory(null, child);
            }
        }

        return PsiManager.getInstance(project).findDirectory(childFile);
    }

    public static void writeFile(AnActionEvent anActionEvent, Project project, String fullPck, String className, String generateCode, FileType fileType) {
        VirtualFile thisVirtualFile = anActionEvent.getData(LangDataKeys.VIRTUAL_FILE);
        VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(thisVirtualFile);

        WriteCommandAction.runWriteCommandAction(project, () -> {
            try {
                PsiDirectory directory;
                try {
                    directory = LocalFileUtils.getChildDirNotExistCreate(project,
                            contentRoot, fullPck);
                } catch (IOException ex) {
                    throw new RuntimeException("find or create directory error: ", ex);
                }
                PsiFile generateEntityFile = PsiFileFactory.getInstance(project)
                        .createFileFromText(className, fileType, generateCode);

                //格式化代码
                CodeStyleManager.getInstance(project).reformat(generateEntityFile);

                directory.add(generateEntityFile);

            } catch (Exception ex) {
                // 弹框提示
                Messages.showMessageDialog(ex.getMessage(), "error massage:", Messages.getErrorIcon());
            }
        });
    }
}
